package com.rb.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.aliyuncs.exceptions.ClientException;
import com.rb.model.Robot;
import com.rb.model.Secret_key;
import com.rb.model.User;
import com.rb.service.UserServiceDAO;
import com.rb.util.ParseJson;
import com.rb.util.SendMessage;
import com.rb.util.SetSecretKey;

import net.sf.json.JSONObject;

/**
 * @author 作者 :ZYY
 * @version 创建时间：2016年12月16日 上午11:25:29
 */
@Controller
public class UserController {
	@Autowired
	private UserServiceDAO userServiceDAO;

	/*@RequestMapping(value = "index")
	public String getindesx(HttpServletRequest request, HttpServletResponse response) {
		List<Robot> robotList = userServiceDAO.showAllRobot();
		HttpSession session = request.getSession();
		session.setAttribute("robotList", robotList);
		return "index";
	}
	@RequestMapping(value = "userInfo")
	public String getUserInfo(HttpServletRequest request, HttpServletResponse response) {
		List<User> userList = userServiceDAO.showAllUser();
		HttpSession session = request.getSession();
		session.setAttribute("userList", userList);
		return "userInfo";
	}
	@RequestMapping(value = "login")
	public String login(HttpServletRequest request, HttpServletResponse response) {
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		if ("yanfa123".equals(account) && "159357".equals(password)) {
			return "redirect:index.do";
		}
		return "login";
	}
	
	@RequestMapping(value = "deleteRobot")
	public String deleteRobot(HttpServletRequest request, HttpServletResponse response) {
		String uid = request.getParameter("uid");
		userServiceDAO.deleteRobotByUid(uid);
		return "redirect:index";
	}
	@RequestMapping(value = "deleteUser")
	public String deleteUser(HttpServletRequest request, HttpServletResponse response) {
		String account = request.getParameter("account");
		userServiceDAO.deleteUserByAccount(account);
		return "redirect:userInfo";
	}*/
	
	// 机器人出库请求相应
	@RequestMapping(value = "outWarehouse", method = RequestMethod.POST)
	@ResponseBody
	public void addRobot(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();
		String[] str = { "uid" };

		Map<String, Object> map = ParseJson.otherDo(data, str);
		if ((boolean) map.get("flag")) {
			String uid = map.get("uid").toString();
			Timestamp time = getNowTime();
			String name = "小雪";
			Robot robot = new Robot(uid, name, "0", 0, null, time);
			// 向数据库添加数据
			backmap = userServiceDAO.addRobot(robot);
			json.put("flag", backmap.get("flag"));
			json.put("message", backmap.get("message"));
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}

		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 主人注册（机器人端）
	@RequestMapping(value = "masterRegister", method = RequestMethod.POST)
	@ResponseBody
	public void masterRegister(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();
		Map<String, Object> map = ParseJson.masterR(data);
		System.out.println(map);
		if ((boolean) map.get("flag")) {
			String uid = map.get("uid").toString();
			String account = map.get("mobile").toString();
			String password = map.get("password").toString();
			// 验证码服务
			String auth_code = map.get("auth_code").toString();
			Timestamp time = getNowTime();
			String nickName = map.get("nickname").toString();
			User user = new User(account, password, nickName, 0, 0, time, null, "");
			backmap = userServiceDAO.addUser(user, uid, auth_code);
			json.put("flag", backmap.get("flag"));
			json.put("message", backmap.get("message"));
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}

		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 用户注册（手机端）
	@RequestMapping(value = "userRegister", method = RequestMethod.POST)
	@ResponseBody
	public void userRegister(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();

		Map<String, Object> map = ParseJson.register2(data);
		if ((boolean) map.get("flag")) {
			String account = map.get("mobile").toString();
			String password = map.get("password").toString();
			String auth_code = map.get("auth_code").toString();
			String nickname = map.get("nickname").toString();
			String head = map.get("head").toString();
			String head_name = map.get("head_name").toString();

			Timestamp time = getNowTime();
			User user = new User(account, password, nickname, 2, 0, time, head, head_name);
			backmap = userServiceDAO.addUser1(user, auth_code);
		}

		json.put("flag", backmap.get("flag"));
		json.put("message", backmap.get("message"));
		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 验证码获取
	@RequestMapping(value = "getAuthCode", method = RequestMethod.POST)
	@ResponseBody
	public void getAuthCode(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException, ClientException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		String str = "0";
		boolean flag = false;
		Map<String, Object> backmap = new HashMap<>();

		Map<String, Object> map = ParseJson.register1(data);
		if ((boolean) map.get("flag")) {

			String account = map.get("mobile").toString();
			String auth_code = SetSecretKey.getCreditCode();

			Timestamp time = getNowTime();
			flag = SendMessage.sample(auth_code, account);
			backmap = userServiceDAO.addAuthCode(account, auth_code, time);
			if (flag && "true".equals(backmap.get("flag").toString())) {
				str = auth_code;
			}
			json.put("flag", backmap.get("flag"));
			json.put("message", backmap.get("message"));
			json.put("code", str);
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
			json.put("code", str);
		}

		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 修改机器人信息
	@RequestMapping(value = "updateRobot", method = RequestMethod.POST)
	@ResponseBody
	public void updateRobot(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();

		String[] str = { "uid", "name" };
		Map<String, Object> map = ParseJson.otherDo(data, str);
		if ((boolean) map.get("flag")) {
			String uid = map.get("uid").toString();
			String newName = map.get("name").toString();
			Timestamp time = getNowTime();
			backmap = userServiceDAO.updateRobot(uid, newName, time);
			json.put("flag", backmap.get("flag"));
			json.put("message", backmap.get("message"));
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}
		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 用户登录
	@RequestMapping(value = "userLogin", method = RequestMethod.POST)
	@ResponseBody
	public void userLogin(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();

		Map<String, Object> map = ParseJson.login(data);
		if ((boolean) map.get("flag")) {
			String account = map.get("mobile").toString();
			String password = map.get("password").toString();
			Timestamp time = getNowTime();
			backmap = userServiceDAO.userLogin(account, password, time);

			if ("true".equals(backmap.get("flag").toString())) {
				Secret_key secret_key = userServiceDAO.findSecretKeyByAccount(account);
				User user = userServiceDAO.findUserByAccount(account);
				json.put("secret_key", secret_key.getSr_key());
				json.put("account", account);
				json.put("name", user.getName());
				json.put("head", user.getHead());
				json.put("role", user.getRole());
				json.put("head_name", user.getHead_name());
				json.put("flag", backmap.get("flag"));
				json.put("message", backmap.get("message"));
			} else {
				json.put("flag", backmap.get("flag"));
				json.put("message", backmap.get("message"));
			}
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}
		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 用户登出
	@RequestMapping(value = "userLogout", method = RequestMethod.POST)
	@ResponseBody
	public void userLogout(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();

		String[] str = { "mobile" };
		Map<String, Object> map = ParseJson.otherDo(data, str);

		if ((boolean) map.get("flag")) {
			String account = map.get("mobile").toString();
			Timestamp time = getNowTime();
			backmap = userServiceDAO.userLogout(account, time);
			json.put("flag", backmap.get("flag"));
			json.put("message", backmap.get("message"));
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}
		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 校验机器人当前注册绑定情况
	@RequestMapping(value = "judgeRobotStatus", method = RequestMethod.POST)
	@ResponseBody
	public void judgeRobotStatus(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();

		String[] str = { "uid" };
		Map<String, Object> map = ParseJson.otherDo(data, str);
		if ((boolean) map.get("flag")) {
			String uid = map.get("uid").toString();
			backmap = userServiceDAO.judgeRobotStatus(uid);
			json.put("flag", backmap.get("flag"));
			json.put("message", backmap.get("message"));
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}

		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 校验用户
	@RequestMapping(value = "judgeUserStatus", method = RequestMethod.POST)
	@ResponseBody
	public void judgeUserStatus(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		String[] str = { "mobile" };
		Map<String, Object> map = ParseJson.otherDo(data, str);
		if ((boolean) map.get("flag")) {
			String account = map.get("mobile").toString();
			List<Object> list = userServiceDAO.judgeUserLogin(account);
			Secret_key secret_key = userServiceDAO.findSecretKeyByAccount(account);
			json.put("permission", list.get(0));
			json.put("activate", list.get(1));
			json.put("uid", list.get(2));
			json.put("secret_key", secret_key.getSr_key());
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}

		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 修改用户昵称
	@RequestMapping(value = "changeUserName", method = RequestMethod.POST)
	@ResponseBody
	public void changeUserName(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();

		String[] str = { "mobile", "name" };
		Map<String, Object> map = ParseJson.otherDo(data, str);

		if ((boolean) map.get("flag")) {
			String account = map.get("mobile").toString();
			String name = map.get("name").toString();
			backmap = userServiceDAO.changeUserName(account, name);
			json.put("flag", backmap.get("flag"));
			json.put("message", backmap.get("message"));
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}
		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 修改用户头像
	@RequestMapping(value = "changeUserHead", method = RequestMethod.POST)
	@ResponseBody
	public void changeUserHead(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();

		String[] str = { "mobile", "head", "head_name" };
		Map<String, Object> map = ParseJson.otherDo(data, str);
		if ((boolean) map.get("flag")) {
			String account = map.get("mobile").toString();
			String head = map.get("head").toString();
			String head_name = map.get("head_name").toString();
			backmap = userServiceDAO.changeUserHead(account, head, head_name);
			json.put("flag", backmap.get("flag"));
			json.put("message", backmap.get("message"));
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}
		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 忘记用户密码
	@RequestMapping(value = "changeUserPwd", method = RequestMethod.POST)
	@ResponseBody
	public void changeUserPwd(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();

		String[] str = { "mobile", "password", "auth_code" };
		Map<String, Object> map = ParseJson.otherDo(data, str);

		if ((boolean) map.get("flag")) {
			String account = map.get("mobile").toString();
			String password = map.get("password").toString();
			String auth_code = map.get("auth_code").toString();

			backmap = userServiceDAO.changeUserPwd(account, password, auth_code);
			json.put("flag", backmap.get("flag"));
			json.put("message", backmap.get("message"));
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}
		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 修改用户密码
	@RequestMapping(value = "changeUserPwd1", method = RequestMethod.POST)
	@ResponseBody
	public void changeUserPwd1(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();

		String[] str = { "mobile", "password", "newpassword" };
		Map<String, Object> map = ParseJson.otherDo(data, str);

		if ((boolean) map.get("flag")) {
			String account = map.get("mobile").toString();
			String password = map.get("password").toString();
			String newpassword = map.get("newpassword").toString();

			backmap = userServiceDAO.changeUserPwd1(account, password, newpassword);
			json.put("flag", backmap.get("flag"));
			json.put("message", backmap.get("message"));
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}
		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}
	// 修改用户手机号
	@RequestMapping(value = "changeUserMobile", method = RequestMethod.POST)
	@ResponseBody
	public void changeUserMobile(@RequestBody String data, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 定义返回数据
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();
		Map<String, Object> backmap = new HashMap<>();

		String[] str = { "mobile", "auth_code", "newMobile" };
		Map<String, Object> map = ParseJson.otherDo(data, str);

		if ((boolean) map.get("flag")) {
			String account = map.get("mobile").toString();
			String auth_code = map.get("auth_code").toString();
			String newMobile = map.get("newMobile").toString();
			Timestamp time = getNowTime();
			backmap = userServiceDAO.changeUserMobile(account, newMobile, auth_code, time);

			json.put("flag", backmap.get("flag"));
			json.put("message", backmap.get("message"));
		} else {
			json.put("flag", "false");
			json.put("message", "json数据格式或参数类型、大小错误！");
		}
		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();
	}

	// 与服务器端通信
	@RequestMapping(value = "judgeStatus", method = RequestMethod.GET)
	public void judgeStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		String type = request.getParameter("type");
		String id = request.getParameter("id");
		JSONObject newData = new JSONObject();
		JSONObject json = new JSONObject();

		if (type.equals("user")) {
			json = serviceUserJson(type, id);
		} else {
			json = serviceRobotJson(type, id);
		}
		newData.put("data", json);
		PrintWriter pw = response.getWriter();
		pw.print(newData.toString());
		pw.close();

	}

	// 返回用户相关信息
	public JSONObject serviceUserJson(String type, String id) {

		// 定义返回数据
		JSONObject json = new JSONObject();
		JSONObject content = new JSONObject();
		JSONArray contacts = new JSONArray();
		JSONObject robots = new JSONObject();
		// List<Object> list = userServiceDAO.judgeUserLogin(id);
		User user = userServiceDAO.findUserByAccount(id);
		Secret_key secret_key = userServiceDAO.findSecretKeyByAccount(id);
		Date date = new Date();
		if (user != null) {
			json.put("service", "ClientInfo");
			json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z").format(date));
			content.put("id", id);
			content.put("type", "user");
			content.put("exists", true);
			content.put("login", false);
			content.put("loginKey", secret_key.getSr_key());
			if (user.getStatus() == 1) {
				content.put("login", true);
			}
			Robot robot = userServiceDAO.findRobotByAccount(id);
			if (robot != null) {
				robots.put("id", robot.getUid());
				robots.put("type", "robot");
				robots.put("role", "master");
				contacts.add(robots);
			}

			content.put("contacts", contacts);
			json.put("content", content);
		} else {
			json.put("service", "ClientInfo");
			json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z").format(date));
			content.put("id", id);
			content.put("type", "user");
			content.put("exists", false);
			content.put("login", false);
			content.put("loginKey", "");
			content.put("contacts", contacts);
			json.put("content", content);
		}
		return json;
	}

	// 返回机器人相关信息
	public JSONObject serviceRobotJson(String type, String id) {
		// 定义返回数据
		JSONObject json = new JSONObject();
		JSONObject content = new JSONObject();
		JSONArray contacts = new JSONArray();
		JSONObject users = new JSONObject();
		Robot robot = userServiceDAO.findRobotByUid(id);
		Date date = new Date();
		if (robot != null) {
			json.put("service", "ClientInfo");
			json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z").format(date));
			content.put("id", id);
			content.put("type", "robot");
			content.put("exists", true);
			User user = userServiceDAO.findUserByAccount(robot.getMaster_account());
			if (user == null) {
				json.put("service", "ClientInfo");
				json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z").format(date));
				content.put("id", id.toString());
				content.put("type", "robot");
				content.put("exists", false);
				content.put("contacts", contacts);
				json.put("content", content);
			}else {
				users.put("id", user.getAccount());
				users.put("type", "user");
				users.put("role", "master");
				contacts.add(users);
				content.put("contacts", contacts);
				json.put("content", content);
			}
			
		} else {
			json.put("service", "ClientInfo");
			json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z").format(date));
			content.put("id", id.toString());
			content.put("type", "robot");
			content.put("exists", false);
			content.put("contacts", contacts);
			json.put("content", content);
		}
		return json;
	}

	// 格式化当前时间方法
	public Timestamp getNowTime() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Timestamp time = Timestamp.valueOf(dateFormat.format(new Date()));
		return time;
	}

}
